import os
import utils
import collect
from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill, Border, Side, Alignment
import datetime

today = datetime.date.today()  # 今天
yest = today - datetime.timedelta(days=1)
fill_date = PatternFill(
    fill_type='solid', start_color='D9FDE900', end_color='D9FDE900')
fill_main = PatternFill(
    fill_type='solid', start_color='C6FDCC00', end_color='C6FDCC00')
fill_alt = PatternFill(
    fill_type='solid', start_color='BCD7E400', end_color='BCD7E400')

thin = Side(border_style="thin", color="000000")
border_normal = Border(top=thin, bottom=thin, left=thin, right=thin)
align_header = Alignment(horizontal='center')
align_header_v = Alignment(vertical='center', wrap_text=True)



# 设置单元格宽度
def set_columns_width(sheet, columns_width):
    for index, width in enumerate(columns_width):
        sheet.column_dimensions[get_column_letter(index + 1)].width = width

# 拼接基本信息
def get_basic_data(b):
    return [b.get('nickname'), b.get('gh_id')]

def set_border(rows):
    for row in rows:
        for cell in row:
            cell.border = border_normal


def set_styles(rows, fill=None, alignment=None):
    for row in rows:
        for cell in row:
            if fill:
                cell.fill = fill
            if alignment:
                cell.alignment = alignment


# 生成表格
class ReportGenerator:
    def __init__(self, library, date_to_report):
        """
        :param utils.AccountLibrary library:
        :param date_to_report:
        """
        self.date = date_to_report
        self.library = library
        self.gh_id = None

    # 读取基础信息
    def get_basic(self, gh_id):
        date = self.date
        if self.date == utils.get_today():
            date = utils.get_yesterday()
        return utils.get_json_file(gh_id, date, 'basic.json')


    # 读取访问人数信息
    def get_visitors_list(self, gh_id):
        return utils.get_json_file(gh_id, self.date, 'app-msg-visitors-info.json')

    # 读取访问累计信息
    def get_visitors_data(self, gh_id):
        return utils.get_json_file(gh_id, self.date, 'app-msg-visitors-data.json')

    # 读取新增留存
    def get_new_retained(self, gh_id):
        return utils.get_json_file(gh_id, self.date, 'app-New-retained.json')

    # 读取流量主数据
    def get_publish_info(self, gh_id):
        return utils.get_json_file(gh_id, self.date, 'app-publish-info.json')

    def save_excel(self, workbook, name):
        filename = 'output/{} {}.xlsx'.format(self.date, name)
        try:
            workbook.save(filename)
            workbook.close()
        except PermissionError:
            print('无法写入{}，请检查是否在Excel中打开了文件，如有需要请另存为并关闭'.format(filename))

    def make_today_ad(self):
        os.makedirs('output', exist_ok=True)
        self.make_samllprogram_data()

    def make_samllprogram_data(self):
        workbook, sheet = utils.make_workbook()
        set_columns_width(
            sheet, [20, 16, 12, 12, 12, 12, 12, 12, 12, 12])
        sheet.append(['日期', self.date])
        sheet.append(['名称', '原始ID', '累计访问人数', '新访问人数', '昨日访问人数', '分享人数', '活跃留存(%)',
                      '曝光量', '点击量', '广告收入(元)'])
        row_index = 2
        for gh_id in self.library.get_account_list():
            bb = self.get_basic(gh_id)
            a = self.get_visitors_list(gh_id)
            b = self.get_visitors_data(gh_id)
            c = self.get_new_retained(gh_id)
            d = self.get_publish_info(gh_id)
            sheet.append(get_basic_data(bb) + [
                b.get("visitors"), a.get("yest_visitor"), a.get("new_visitors"), a.get("Share_number"),
                c.get("new_retain"), d.get("Exposure"), d.get("click"), d.get("income")
            ])
        sheet['A1'].fill = fill_date
        set_styles(sheet['A2:J2'], fill_main, align_header)
        set_styles(sheet['A2:J{}'.format(row_index)], alignment=align_header_v)
        self.save_excel(workbook, "小程序数据")
        for gh_id in self.library.get_account_list():
            try:
                os.remove('data/{0}/{1}/app-msg-visitors-info.json'.format(gh_id, self.date))
            except (FileNotFoundError):
                pass
            try:
                os.remove('data/{0}/{1}/app-msg-visitors-data.json'.format(gh_id, self.date))
            except (FileNotFoundError):
                pass
            try:
                os.remove('data/{0}/{1}/app-New-retained.json'.format(gh_id, self.date))
            except (FileNotFoundError):
                pass
            try:
                os.remove('data/{0}/{1}/app-publish-info.json'.format(gh_id, self.date))
            except (FileNotFoundError):
                pass


if __name__ == '__main__':
    date_time = input("请输入日期，如{0} （按Enter）默认是昨天:  ".format(yest))
    collect.test_collect(date_time)
    reporter = ReportGenerator(
        utils.default_library(), date_time if date_time else utils.get_yesterday())
    reporter.make_today_ad()